package com.acme.multithreadinglab.pooledconnection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;

import javax.sql.DataSource;

public class BlockingConnectionPool implements ConnectionPool {
	private int maxConns;
	private DataSource ds;
	private BlockingQueue<Connection> connections;

	public BlockingConnectionPool(DataSource ds, int maxConns) throws SQLException {
		this.ds = ds;
		this.maxConns = maxConns;
		
		connections = new ArrayBlockingQueue<Connection>(maxConns);
		
		for (int i=0; i < maxConns; i++) {
			connections.add(createConnection());
		}
	}
	
	@Override
	public Connection getConnection() throws InterruptedException, SQLException {
		return connections.take();
	}

	@Override
	public void release(Connection connection) {
		try {
			connection.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		connections.add(connection);
	}
	
	private Connection createConnection() throws SQLException {
		return ds.getConnection();
	}
}
